<?php
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';

$max = 999999999999; 

if (isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['error'] == 0) {
  $upload_file = $_FILES['Filedata'];
  $file_info = pathinfo($upload_file['name']);
  $file_name = (isset($file_info['filename'])) ? $file_info['filename'] : '';
  $file_ext = (isset($file_info['extension'])) ? $file_info['extension'] : '';
  
  $folder = basename(dirname(__FILE__));
  $obj_id = $_POST['id'];
  $myPdo = DbUtils::createPdoInst();
  $cond_vals = new stdClass();
  $cond_vals->c = 't.id = :v1';
  $cond_vals->v = array(':v1' => $obj_id);
  $obj = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . $folder, $cond_vals, NULL, NULL, 1, 1, NULL)->d[0];
  $obj_path = iconv('UTF-8', 'GB2312', $obj->file);
  
  $width_tn = 800;
  $height_tn = 400;
  
  $upload_path = "../../../uploads/exts/plugins/$folder/";
  MiscUtils::create($upload_path);
  
  $file_name = iconv('UTF-8', 'GB2312', $file_name);
  $file_name_re = $file_name . '_' . MiscUtils::unique();
  $path = $upload_path . $file_name_re . '.' . $file_ext;
  $path_tn = $upload_path . $file_name_re . '_tn';
  
  if (file_exists($path)) {
    @unlink($path);
  }
  if (file_exists("$path_tn.jpg")) {
    @unlink("$path_tn.jpg");
  }
  
  $size = filesize($upload_file['tmp_name']);
  if ($size < $max) {
    $im = NULL;
    if (strtolower($file_ext) == 'jpg' || strtolower($file_ext) == 'jpeg') {
      $im = imagecreatefromjpeg($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'png') {
      $im = imagecreatefrompng($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'gif') {
      $im = imagecreatefromgif($upload_file["tmp_name"]);
    }
    if ($im) {
      MiscUtils::resize($im, $width_tn, $height_tn, $path_tn);
      ImageDestroy($im);
      @unlink($upload_file['tmp_name']);

      $obj->file = iconv('GB2312', 'UTF-8', "$path_tn.jpg");
    } else {
      exit(0);
    }
  } else {
    if (move_uploaded_file($upload_file['tmp_name'], $path)) {
      $obj->file = iconv('GB2312', 'UTF-8', $path);
    }
  }
  
  if (file_exists($obj_path)) {
    @unlink($obj_path);
  }
  DbUtils::update($myPdo, TABLE_NAME_PREFIX_PLUGIN . $folder, $obj);
  echo json_encode($obj);
}
?>